package light.head.controller.oa;

import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.config.ConfigParm;
import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.oa.DocumentInfoDAO;
import light.head.dao.oa.DocumentTypeDAO;
import light.head.dao.sys.FileDAO;
import light.head.dao.sys.OrganDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.DownLoadUtils;
import light.head.model.Authority;
import light.head.model.DocumentInfo;
import light.head.model.DocumentType;
import light.head.model.FileInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = Url.C_DOCUMENTINFO)
public class DocumentInfoController extends SupporterController{
	
	private final static String documentintInfo_file = "upload/documentintInFile/";

	private DocumentInfoDAO documentDAO;
	private DocumentTypeDAO dtDAO;
	private FileDAO fDAO;
	private OrganDAO organDAO;
	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.DOCUMENTINFO_INIT);
	}
	
	@RequestMapping(Url.QUERY)
	public ModelAndView query(String dc, HttpServletRequest request, HttpServletResponse response) {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.DC, Parm.CU,  Parm.TIME1,Parm.TIME2, Parm.OC, Parm.RC,Parm.NAME,Parm.CN);
		
		//  权限所必须的三个参数
		map.put(Parm.PC, cu_code(request).toString());
		map.put(Parm.OC, cu_organCode(request).toString());
		map.put(Parm.RC, (null == cu_roleCode(request)) ? "" : cu_roleCode(request).toString());
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if (RESULT.SUCCESS == documentDAO.findByMap(organDAO.getSonCodeList(oc),map, pb)) {
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.DOCUMENTINFO_LIST);
	}
	
	@Transactional
	@RequestMapping(Url.UPLOADS)
	public void uploads(Integer code, HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequestd = (MultipartHttpServletRequest) request;
		List<MultipartFile> files = multipartRequestd.getFiles("files");

		StringBuffer result = new StringBuffer("");
		if (null != files && files.size() > 0) {

			String name = null;
			String ext = null;
			String uuid = null;
			String path = null;
			String savePath = null;
			UUID u = null;

			for (MultipartFile mf : files) {
				name = mf.getOriginalFilename();
				if (isNotNull(name)) {
					ext = name.substring(name.lastIndexOf('.') + 1);
					if (!ext.toUpperCase().equals(Sys.JPG)
							&& !ext.toUpperCase().equals(Sys.GIF)
							&& !ext.toUpperCase().equals(Sys.JPEG)
							&& !ext.toUpperCase().equals(Sys.BMP)
							&& !ext.toUpperCase().equals(Sys.PNG)
							&& !ext.toUpperCase().equals(Sys.XLSX)
							&& !ext.toUpperCase().equals(Sys.XLS)
							&& !ext.toUpperCase().equals(Sys.DOCX)
							&& !ext.toUpperCase().equals(Sys.DOC)
							&& !ext.toUpperCase().equals(Sys.PDF)
							&& !ext.toUpperCase().equals(Sys.PPT)
							&& !ext.toUpperCase().equals(Sys.RAR)
							&& !ext.toUpperCase().equals(Sys.ZIP)) {
						print(response, Msg.J_FILE_TYPE_ERROR);
						return;
					}
					name = name.substring(0, name.lastIndexOf('.'));

					u = UUID.randomUUID();
					uuid = u.toString().replace("-", "");
					path = documentintInfo_file + uuid + Sys.DOT + ext;
					savePath = ConfigParm.getProjectPath() + path;
					FileOutputStream fo;
					int size = 0;
					try {
						fo = new FileOutputStream(savePath);
						size = mf.getBytes().length;
						fo.write(mf.getBytes());
						fo.close();
					} catch (Exception e) {
						print(response, Msg.ERROR);
						e.printStackTrace();
					}
					FileInfo f = new FileInfo();
					
					f.setDeleted(false);
					f.setExt(ext);
					f.setName(name);
					f.setCt(new Date());
					f.setModule(Parm.DOCUMENT_DOCUMENTINFO);
					f.setCu(cu_code(request));
					f.setOc(cu_organCode(request));
					f.setSize(size);
					f.setUuid(uuid);
					documentDAO.add(f);
					result.append("{\"code\":\"" + f.getCode() + "\"},");
				}
			}
			result.insert(0, "{\"result\":\"success\",\"list\":[").deleteCharAt(result.length() - 1).append("]}");
			print(response, result.toString());
		} else {
			result.append("{\"result\":\"not_find_file\"}");
		}
	}
	
	@Transactional
	@RequestMapping(value = Url.DOWNLOAD)
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
		}
		FileInfo fi = fDAO.getByUuid(code);
		DocumentInfo d = documentDAO.getByUuid(code);
		if (null == fi) {
		}
		DownLoadUtils.downLoad(documentintInfo_file, d.getName(), fi.getUuid(), fi.getExt(), response);
	}
	
	@RequestMapping(Url.SAVE)
	public void save(DocumentInfo d, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if (null != d.getList() && d.getList().size() > 0) {
			for (DocumentInfo doc : d.getList()) {
				if(doc.getName() == null){
					continue;
				}
				if (doc.getCode() == null) {
					List<DocumentType> iac = dtDAO.findByNameOc(doc.getDn(), cu_organCode(request));
					if (iac == null || iac.size() == 0)  {
						DocumentType atn = new DocumentType();
						atn.setCu(cu_code(request));
						atn.setCt(new Date());
						atn.setDeleted(false);
						atn.setName(doc.getDn());
						atn.setOc(cu_organCode(request));
						dtDAO.add(atn);
						doc.setDc(atn.getCode());
					}else {
						doc.setDc(iac.get(0).getCode());
					}
					
					doc.setCt(new Date());
					doc.setCu(cu_code(request));
					doc.setDeleted(false);
					doc.setOc(cu_organCode(request));
					result = documentDAO.add(doc);
					
					if (null != doc.getpType() && doc.getpType().intValue() > 2 && null != doc.getPublicList() && doc.getPublicList().size() > 0) {
						for (Authority a : doc.getPublicList()) {
							a.setDc(doc.getCode());
							a.setpType(doc.getpType());
							result = documentDAO.add(a);
						}
					}
				} else {
					DocumentInfo di = documentDAO.get(doc.getCode());
					List<DocumentType> iac = dtDAO.findByNameOc(doc.getDn(), cu_organCode(request));
					if (iac == null || iac.size() == 0)  {
						DocumentType atn = new DocumentType();
						atn.setCu(cu_code(request));
						atn.setCt(new Date());
						atn.setDeleted(false);
						atn.setName(doc.getDn());
						atn.setOc(cu_organCode(request));
						dtDAO.add(atn);
						di.setDc(atn.getCode());
					}else{
						di.setDc(iac.get(0).getCode());
					}
					di.setName(doc.getName());
					di.setpType(doc.getpType());
					documentDAO.upd(di);
					List<Authority> aList = documentDAO.getDc(doc.getCode());
					if (aList != null && aList.size() != 0){
						for (Authority a : aList) {
							documentDAO.del(a);
						}
					} 
					if (null != doc.getpType() && doc.getpType().intValue() > 2 && null != doc.getPublicList() && doc.getPublicList().size() > 0) {
						for (Authority a : doc.getPublicList()) {
							a.setDc(doc.getCode());
							a.setpType(doc.getpType());
							result = documentDAO.add(a);
						}
					}
				}
			}
		}
		if (RESULT.SUCCESS == result) {
			print(response, Msg.SUCCESS);
		} else
			print(response, Msg.ERROR);
	}
	
	
	
	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);	// 已上传文档的编号集合 
		if (null != code) {
			String[] codes = code.split(",");
			Integer[] c = new Integer[codes.length];
			int i = 0;
			for (String s : codes) {
				c[i] = Integer.parseInt(s);
				i++;
			}
			List<DocumentType> typeList = dtDAO.findAllByOc(cu_organCode(request));
			if (null != typeList && typeList.size() > 0) {
				StringBuffer result = new StringBuffer("[");
				
				for (DocumentType type : typeList){
					result.append("{");
					result.append("\"dn\":\"" + type.getName() +"\",");
					result.append("\"dc\":\"" + type.getCode() +"\"");
					result.append("},");
				}
				result.deleteCharAt(result.length() - 1).append("]");
				request.setAttribute(Parm.TYPE, result.toString());
			}
			List<FileInfo> di = fDAO.getByCodes(c);
			request.setAttribute(Parm.LIST, di);	// 已上传文档的信息	
		}
		 
		
		return new ModelAndView(Url.DOCUMENTINFO_EDIT);
	}
	
	@RequestMapping(value = Url.EDIT1)
	public ModelAndView edit1(Integer code,HttpServletRequest request,HttpServletResponse response) throws Exception {
		if (null != code) {
			List<DocumentType> typeList = dtDAO.findAllByOc(cu_organCode(request));
			if (null != typeList && typeList.size() > 0) {
				StringBuffer result = new StringBuffer("[");
				for (DocumentType type : typeList) {
					result.append("{");
					result.append("\"dn\":\"" + type.getName() +"\",");
					result.append("\"dc\":\"" + type.getCode() +"\"");
					result.append("},");
				}
				result.deleteCharAt(result.length() - 1).append("]");
				request.setAttribute(Parm.TYPE, result.toString());
			}
			List<DocumentInfo> di = documentDAO.getByCode(code);
			for (DocumentInfo d : di) {
				d.setPublicList(documentDAO.getDc(d.getCode()));
			}
			List<Object> p = documentDAO.findByCode(code);
			request.setAttribute(Parm.P, p);
			request.setAttribute(Parm.LIST, di);	// 已上传文档的信息	
		}
		return new ModelAndView(Url.DOCUMENTINFO_EDIT1);
	}
	
	/**
	 * 查询公开机构
	 */
	@RequestMapping(Url.AID_INIT_1)
	public ModelAndView aidOrganInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.P, request.getParameter(Parm.P));
		String a = request.getParameter(Parm.A);
		request.setAttribute(Parm.A, a);
		String type = request.getParameter(Parm.TYPE);
		request.setAttribute(Parm.TYPE, type);
		return new ModelAndView(Url.DOCUMENTINFO_ORGAN_INIT);
	}
	
	@RequestMapping(Url.AID_LIST_1)
	public ModelAndView aidOrganList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.REAL_NAME, Parm.OC,Parm.SUC);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if (RESULT.SUCCESS == documentDAO.findOrgan(organDAO.getSonCodeList(oc), map, pageBean)) {
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		}
		return new ModelAndView(Url.DOCUMENTINFO_ORGAN_LIST);
	}
	
	/**
	 * 查询公开角色
	 */
	@RequestMapping(Url.AID_INIT_2)
	public ModelAndView aidRoleInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.P, request.getParameter(Parm.P));
		String a = request.getParameter(Parm.A);
		request.setAttribute(Parm.A, a);
		String type = request.getParameter(Parm.TYPE);
		request.setAttribute(Parm.TYPE, type);
		return new ModelAndView(Url.DOCUMENTINFO_ROLR_INIT);
	}

	@RequestMapping(Url.AID_LIST_2)
	public ModelAndView aidRoleList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME, Parm.SUC);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if (RESULT.SUCCESS == documentDAO.findSubRole(organDAO.getSonCodeList(oc), map, pageBean)) {
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		}
		return new ModelAndView(Url.DOCUMENTINFO_ROLE_LIST);
	}

	/**
	 * 查询公开人
	 */
	@RequestMapping(Url.AID_INIT)
	public ModelAndView aidUserInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.P, request.getParameter(Parm.P));
		String a = request.getParameter(Parm.A);
		request.setAttribute(Parm.A, a);
		String type = request.getParameter(Parm.TYPE);
		request.setAttribute(Parm.TYPE, type);
		return new ModelAndView(Url.DOCUMENTINFO_USER_INIT);
	}

	@RequestMapping(Url.AID_LIST)
	public ModelAndView aidUserList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.REAL_NAME, Parm.SUC, Parm.OC);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if (RESULT.SUCCESS == documentDAO.findSubUsers(organDAO.getSonCodeList(oc), map, pageBean)) {
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		}
		return new ModelAndView(Url.DOCUMENTINFO_USER_LIST);
	}
	
	@Autowired
	public void setDocumentDAO(DocumentInfoDAO documentDAO) {
		this.documentDAO = documentDAO;
	}

	@Autowired
	public void setfDAO(FileDAO fDAO) {
		this.fDAO = fDAO;
	}

	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	@Autowired
	public void setDtDAO(DocumentTypeDAO dtDAO) {
		this.dtDAO = dtDAO;
	}
	
}
